package com.ucode.admin.cgms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.admin.base.core.CurrentLoginUserService;
import com.ucode.cgms.service.CgmsCompanionUserService;
import com.ucode.member.service.MemberService;
import com.ucode.model.cgms.CgmsCompanionUser;
import com.ucode.model.cgms.convert.CgmsCompanionUserConvert;
import com.ucode.model.cgms.enums.CgmsCompanionUserStatuzEnum;
import com.ucode.model.cgms.enums.CgmsCompanionUserWorkStateEnum;
import com.ucode.model.cgms.enums.CgmsSysResultCodeEnum;
import com.ucode.model.cgms.form.CgmsAuditForm;
import com.ucode.model.cgms.form.CgmsCompanionUserApplyForm;
import com.ucode.model.cgms.vo.CgmsCompanionUserVO;
import com.ucode.model.member.Member;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.CommonAuditStatusEnum;
import com.ucode.tool.base.enums.CommonSwitchStatusEnum;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.base.enums.UserTypeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.*;

@Tag(name = "管理后台 - 陪玩社区系统 - 陪玩用户")
@RestController
@RequestMapping("/cgms/companion-user")
@Validated
public class CgmsCompanionUserController {

    @Resource
    private CgmsCompanionUserService cgmsCompanionUserService;
    @Resource
    private CurrentLoginUserService currentLoginUserService;
    @Resource
    private MemberService memberService;

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-user:query')")
    public ResponseResult<Paginator<CgmsCompanionUserVO>> pageList(
            @Schema(description = "类型") @RequestParam(value = "type",required = false) Integer type,
            @Schema(description = "担保人") @RequestParam(value = "guarantorId",required = false) Long guarantorId,
            @Schema(description = "昵称") @RequestParam(value = "nickName",required = false) String nickName,
            @Schema(description = "真实姓名") @RequestParam(value = "realName",required = false) String realName,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "微信号") @RequestParam(value = "wechatId",required = false) String wechatId,
            @Schema(description = "支付宝账号") @RequestParam(value = "alipayAccount",required = false) String alipayAccount,
            @Schema(description = "身份证号") @RequestParam(value = "idCardNumber",required = false) String idCardNumber,
            @Schema(description = "工作状态") @RequestParam(value = "workStatus",required = false) Integer workStatus,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(nickName))
            condition.put("nickName", StrUtil.concat(true,"%", nickName,"%"));
        if(StrUtil.isNotBlank(realName))
            condition.put("realName", StrUtil.concat(true,"%", realName,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));
        if(StrUtil.isNotBlank(wechatId))
            condition.put("wechatId", StrUtil.concat(true,"%", wechatId,"%"));
        if(StrUtil.isNotBlank(alipayAccount))
            condition.put("alipayAccount", StrUtil.concat(true,"%", alipayAccount,"%"));
        if(StrUtil.isNotBlank(idCardNumber))
            condition.put("idCardNumber", StrUtil.concat(true,"%", idCardNumber,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("type",type);
        condition.put("gender",gender);
        condition.put("guarantorId",guarantorId);
        condition.put("workStatus",workStatus);
        condition.put("deltag",false);

        return ResponseResult.success(this.pageList(condition,pageNum,pageSize));
    }


    @GetMapping("/page-apply-list")
    @Operation(summary = "获得申请分页列表")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-user:query-apply')")
    public ResponseResult<Paginator<CgmsCompanionUserVO>> pageApplyList(
            @Schema(description = "昵称") @RequestParam(value = "nickName",required = false) String nickName,
            @Schema(description = "真实姓名") @RequestParam(value = "realName",required = false) String realName,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "微信号") @RequestParam(value = "wechatId",required = false) String wechatId,
            @Schema(description = "支付宝账号") @RequestParam(value = "alipayAccount",required = false) String alipayAccount,
            @Schema(description = "身份证号") @RequestParam(value = "idCardNumber",required = false) String idCardNumber,
            @Schema(description = "状态,参见 CommonAuditStatusEnum 枚举类",allowableValues = {"1","2","3","4"}) @RequestParam(value = "auditStatuz",required = false) Integer auditStatuz,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(nickName))
            condition.put("nickName", StrUtil.concat(true,"%", nickName,"%"));
        if(StrUtil.isNotBlank(realName))
            condition.put("realName", StrUtil.concat(true,"%", realName,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));
        if(StrUtil.isNotBlank(wechatId))
            condition.put("wechatId", StrUtil.concat(true,"%", wechatId,"%"));
        if(StrUtil.isNotBlank(alipayAccount))
            condition.put("alipayAccount", StrUtil.concat(true,"%", alipayAccount,"%"));
        if(StrUtil.isNotBlank(idCardNumber))
            condition.put("idCardNumber", StrUtil.concat(true,"%", idCardNumber,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("auditStatuz",auditStatuz);
        condition.put("deltag",false);

        return ResponseResult.success(this.pageList(condition,pageNum,pageSize));
    }

    @GetMapping("/list-simple-page")
    @Operation(summary = "分页获取精简信息列表(没有权限校验，公共查询接口)", description = "主要用于前端的下拉选项")
    public ResponseResult<Paginator<CgmsCompanionUser>> simplePageList(@Schema(description = "名称")  @RequestParam(value = "name",required = false) String name,
                                                                      @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                      @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(name))
            condition.put("name", StrUtil.concat(true,"%", name,"%"));
        condition.put("statuz",CommonSwitchStatusEnum.ENABLE.code);
        condition.put("deltag",false);

        Paginator<CgmsCompanionUser> paginator = cgmsCompanionUserService.queryPageForList(condition,pageSize,pageNum);
        return ResponseResult.success(paginator);
    }

    @GetMapping("/getById/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-user:query')")
    public ResponseResult<CgmsCompanionUser> getById(@PathVariable(name="id",required=true) Long id){
        CgmsCompanionUser bean = cgmsCompanionUserService.validate(id);
        return ResponseResult.success(bean);
    }

    @PostMapping("/create/{memberId}")
    @Parameter(description="用户ID",name = "memberId", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "创建")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-user:create')")
    public ResponseResult<Long> create(@PathVariable(name="id",required=true) Long memberId,
            @Valid @RequestBody CgmsCompanionUserApplyForm form) {
        CgmsCompanionUser bean = CgmsCompanionUserConvert.INSTANCE.convert(form);
        bean.setId(IdentifyUtils.getDefaultSnowflakeId());
        CgmsCompanionUser companionUserDB = cgmsCompanionUserService.selectByPrimaryKey(memberId);
        //验证用户是否已是陪玩用户
        if(ObjUtil.isNotNull(companionUserDB) && !companionUserDB.getDeltag()){

            //待审核
            if(ObjUtil.equals(companionUserDB.getAuditStatuz(), CommonAuditStatusEnum.SUBMIT_REVIEW.getCode())){
                throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_USER_UNDER_REVIEW);
            }

            //陪玩审核通过，且状态为正常或者冻结，则不能再次申请
            if(ObjUtil.equals(companionUserDB.getAuditStatuz(), CommonAuditStatusEnum.SUCCESS.getCode()) && (
                    ObjUtil.equals(companionUserDB.getStatuz(), CgmsCompanionUserStatuzEnum.NORMAL.getCode()) ||
                            ObjUtil.equals(companionUserDB.getStatuz(), CgmsCompanionUserStatuzEnum.FROZEN.getCode())
            )){
                throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_USER_NOT_REAPPLY);
            }
        }

        CgmsCompanionUser companionUser = CgmsCompanionUserConvert.INSTANCE.convert(form);
        companionUser.setId(memberId);
        companionUser.setDeltag(false);
        companionUser.setAuditStatuz(CommonAuditStatusEnum.SUBMIT_REVIEW.getCode());
        companionUser.setStatuz(CgmsCompanionUserStatuzEnum.APPLY.getCode());
        companionUser.setWorkStatus(CgmsCompanionUserWorkStateEnum.REST.getCode());

        if(ObjUtil.isNotNull(companionUserDB)){
            cgmsCompanionUserService.update(companionUser);
        }else {
            cgmsCompanionUserService.insert(companionUser);
        }

        return ResponseResult.success();
    }

    @PostMapping("/create")
    @Operation(summary = "陪玩申请入驻")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-user:create')")
    public ResponseResult<Object> create(@Valid @RequestBody CgmsCompanionUserApplyForm form) {
        Long userId = currentLoginUserService.getCurrentUserId();
        CgmsCompanionUser companionUserDB = cgmsCompanionUserService.selectByPrimaryKey(userId);
        //验证用户是否已是陪玩用户
        if(ObjUtil.isNotNull(companionUserDB) && !companionUserDB.getDeltag()){

            //待审核
            if(ObjUtil.equals(companionUserDB.getAuditStatuz(), CommonAuditStatusEnum.SUBMIT_REVIEW.getCode())){
                throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_USER_UNDER_REVIEW);
            }

            //陪玩审核通过，且状态为正常或者冻结，则不能再次申请
            if(ObjUtil.equals(companionUserDB.getAuditStatuz(), CommonAuditStatusEnum.SUCCESS.getCode()) && (
                    ObjUtil.equals(companionUserDB.getStatuz(), CgmsCompanionUserStatuzEnum.NORMAL.getCode()) ||
                            ObjUtil.equals(companionUserDB.getStatuz(), CgmsCompanionUserStatuzEnum.FROZEN.getCode())
            )){
                throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_USER_NOT_REAPPLY);
            }
        }

        CgmsCompanionUser companionUser = CgmsCompanionUserConvert.INSTANCE.convert(form);
        companionUser.setId(userId);
        companionUser.setDeltag(false);
        companionUser.setAuditStatuz(CommonAuditStatusEnum.SUBMIT_REVIEW.getCode());
        companionUser.setStatuz(CgmsCompanionUserStatuzEnum.APPLY.getCode());
        companionUser.setWorkStatus(CgmsCompanionUserWorkStateEnum.REST.getCode());

        if(ObjUtil.isNotNull(companionUserDB)){
            cgmsCompanionUserService.update(companionUser);
        }else {
            cgmsCompanionUserService.insert(companionUser);
        }
        return ResponseResult.success();
    }
    @PostMapping("/update/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "修改")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-user:update')")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
                                         @Valid @RequestBody CgmsCompanionUserApplyForm form) {
        CgmsCompanionUser bean = CgmsCompanionUserConvert.INSTANCE.convert(form);
        bean.setId(id);
        int i = cgmsCompanionUserService.update(bean);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/audit")
    @Operation(summary = "审核")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-user:audit')")
    public ResponseResult<Object> update(@Valid @RequestBody CgmsAuditForm form) {

        List<CgmsCompanionUser> list = cgmsCompanionUserService.selectByPrimaryKeys(form.getIds());
        if(CollUtil.isNotEmpty(list)) {
            for (CgmsCompanionUser companionUser : list) {
                if(!ObjUtil.equals(companionUser.getStatuz(), CgmsCompanionUserStatuzEnum.APPLY.getCode())){
                    throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_USER_NOT_APPLY);
                }

                CgmsCompanionUser bean = new CgmsCompanionUser();
                bean.setId(companionUser.getId());
                bean.setAuditStatuz(form.getStatuz());
                bean.setProcessorId(currentLoginUserService.getCurrentUserId());
                bean.setProcessorType(UserTypeEnum.ADMIN.getCode());
                bean.setProcessTime(LocalDateTime.now());
                bean.setProcessRemark(form.getRemark());

                if(ObjUtil.equals(CommonAuditStatusEnum.SUCCESS.getCode(),  form.getStatuz())){
                    bean.setStatuz(CgmsCompanionUserStatuzEnum.NORMAL.getCode());
                }else {
                    bean.setStatuz(CgmsCompanionUserStatuzEnum.CANCEL.getCode());
                }
                cgmsCompanionUserService.update(bean);
            }
        }

        return ResponseResult.success();
    }

    @PostMapping("/update-status")
    @Operation(summary = "修改状态")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-user:update')")
    public ResponseResult<Boolean> updateStatus(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 20,message = "编号集合数量为1-20条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids,
                                                @Schema(description = "状态",requiredMode = Schema.RequiredMode.REQUIRED,allowableValues = {"2","3","9"})
                                                @RequestParam(value = "status",required = true) Integer status) {

        if(ObjUtil.equals(status,CgmsCompanionUserStatuzEnum.NORMAL.getCode()) ||
                ObjUtil.equals(status,CgmsCompanionUserStatuzEnum.FROZEN.getCode()) ||
                ObjUtil.equals(status,CgmsCompanionUserStatuzEnum.DELETE.getCode())) {
            int i = cgmsCompanionUserService.updateStatus(ids, status);
            return i > 0 ? ResponseResult.success() : ResponseResult.failed();
        }

        throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
    }

    public List<CgmsCompanionUserVO> pageList(Map<String,Object> condition){
        List<CgmsCompanionUser> list = cgmsCompanionUserService.queryObjectForList(condition,0);
        return setAttributeByVo(list);
    }

    private Paginator<CgmsCompanionUserVO> pageList(Map<String, Object> condition, Integer pageNum, Integer pageSize) {
        Paginator<CgmsCompanionUser> paginator = cgmsCompanionUserService.queryPageForList(condition, pageSize, pageNum);
        Paginator<CgmsCompanionUserVO> paginatorVo = CgmsCompanionUserConvert.INSTANCE.convertPage(paginator);
        if (CollUtil.isNotEmpty(paginator.getList())) {
            paginatorVo.setList(setAttributeByVo(paginator.getList()));
        }
        return paginatorVo;
    }

    private List<CgmsCompanionUserVO> setAttributeByVo(List<CgmsCompanionUser> list) {
        List<CgmsCompanionUserVO> listVo = CgmsCompanionUserConvert.INSTANCE.convertList(list);
        if (CollUtil.isNotEmpty(listVo)) {
            Set<Long> userSetIds = new HashSet<>();
            for(CgmsCompanionUserVO vo : listVo){
                if (ObjUtil.isNotNull(vo.getProcessorId())) {
                    userSetIds.add(vo.getProcessorId());
                }
                userSetIds.add(vo.getGuarantorId());
            }

            Map<Long, Member> processorMap = memberService.getMap(userSetIds);
            for(CgmsCompanionUserVO vo : listVo) {
                Member processorInfo = processorMap.get(vo.getProcessorId());
                if (ObjUtil.isNotNull(processorInfo)) {
                    vo.setProcessorNickname(processorInfo.getNickname());
                    vo.setProcessorAvatar(processorInfo.getAvatar());
                }
                Member guarantorInfo = processorMap.get(vo.getGuarantorId());
                if (ObjUtil.isNotNull(guarantorInfo)) {
                    vo.setGuarantorNickname(guarantorInfo.getNickname());
                    vo.setGuarantorAvatar(guarantorInfo.getAvatar());
                }
            }
        }
        return listVo;
    }

}
